package xyz.csmcool.imutil.utils;


import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;
import xyz.csmcool.imutil.ExceptionHandler.CommonException;
import xyz.csmcool.imutil.webVo.ResultCode;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 什锦
 * @Package xyz.csmcool.utils
 * @since 2021/7/31 18:57
 */

public class JwtUtils {
    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";


    /**
     * 生成token字符串的方法
     * @param id
     * @return
     */
    public static String getJwtToken(String id){
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("sjim-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                //设置token主题部分，存储用户信息
                .claim("id", id)
                // 使用SHA256withDSA加密算法
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) {return false;}
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken.replace("Bearer ", ""));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if(StringUtils.isEmpty(jwtToken)) {return false;}
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token获取会员id
     * @param request
     * @return
     */
    public static String getMemberIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        if(StringUtils.isEmpty(jwtToken) || !jwtToken.startsWith("Bearer ")) { return "";}
        Jws<Claims> claimsJws = null;
        try {
            claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken.replace("Bearer ", ""));
        } catch (ExpiredJwtException e) {
            throw new CommonException(ResultCode.CUSTOM_FAIL.setCode(999).setMessage("用户登陆过期，请重新登陆"));
        } catch (UnsupportedJwtException | IllegalArgumentException | SignatureException | MalformedJwtException e) {
            e.printStackTrace();
        }
        Claims claims = claimsJws.getBody();
        return (String)claims.get("id");
    }


}
